<template>
  <el-row>
    <el-col class="login-container" justify="center" align="middle">
      <el-card style="max-width: 480px">
        <template #header>
          <img
            :src="imgUrl"
            style="width: 100%"
          />
        </template>
        <div class="jump-link">
           <el-link underline="never" type="primary" @click="handleChange">{{ fromType?'返回登陆': '注册账号'}}</el-link>
        </div>
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="loginForm"
          :rules="rules"
          label-width="auto"
        >
          <el-form-item prop="userName">
            <el-input v-model="loginForm.userName"  placeholder="手机号">
            <template #prefix>
              <el-icon class="el-input__icon"><Avatar /></el-icon>
            </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="passWord">
            <el-input v-model="loginForm.passWord"  type="password" placeholder="密码">
              <template #prefix>
                <el-icon class="el-input__icon"><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item v-if="fromType" prop="validCode">
            <el-input v-model="loginForm.validCode" type="password" placeholder="验证码">
              <template #append>
                <el-button @click="countdownChange">{{ countDown.validText }}</el-button>
              </template>
             </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)" style="width: 100%">{{ fromType?'注册账号': '登录'}}</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup>
import {ref,reactive,computed,toRaw} from 'vue';
import {getCode,userAuthentication,login,menuPermissions} from '../../api'
import { ElMessage } from 'element-plus'
import 'element-plus/dist/index.css';
import {useRouter} from 'vue-router'
import { useStore } from 'vuex';

//调试手机号13770670680-123456
const store = useStore()
const router=useRouter()
const imgUrl = new URL('../../../public/login-head.png', import.meta.url).href
//拿到路由数据
const routerList=computed(()=> store.state.menu.routerList)

//fromType用于区别登陆页（0）和注册页（1）
const fromType=ref(0)
//用户登陆数据
const loginForm=reactive({
  "userName": '',
  "passWord": '',
  "validCode": ''
})

//验证码计时数据,flag避免重复发送验证码true(计时器已经打开)
const flag=ref(false)
const countDown=reactive({
  validText:'获取验证码',
  time:60
})
const phoneReg=/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
//发送验证码处理
const countdownChange=()=>{
  //不重复处理
  if(flag.value)return
  //校验手机号格式
  if(!phoneReg.test(loginForm.userName)||!loginForm.userName){
    return ElMessage({
      message: '请检查手机号码格式',
      type: 'warning',
      showClose: true, // 显示关闭按钮
      duration: 2000 // 0 表示不自动关闭
    });
  }
  //开启定时器
  const n=setInterval(()=>{
    if(countDown.time<0||countDown.time===0){
      flag.value=false
      countDown.time=60
      countDown.validText='获取验证码'
      clearInterval(n)
    }else{
      countDown.time--
      countDown.validText=`剩余${countDown.time}s`
    }
  },1000)
  flag.value=true

  //发送请求获取验证码
  getCode({tel:loginForm.userName}).then(({data})=>{
    if(data.code===10000){
      ElMessage.success('验证码发送成功！')
    }
  })
}
const ruleFormRef = ref()
//用户名（手机号）验证
const validateUserName = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入用户名'))
  } else {
    if (value !== '') {
      const phoneReg=/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
      if (phoneReg.test(value)) {
          callback()
          return 
      }
      callback(new Error('手机号格式错误'))
    }
  }
}
//密码验证
const validatePassWord = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (value !== '') {
      const passReg=/^[a-zA-Z0-9_-]{4,16}$/
      if (passReg.test(value)){
        callback()
        return 
      }
      callback(new Error('密码格式错误（4-16位字符）'))
    }
    callback()
  }
}
//表单验证规则
const rules = reactive({
  userName: [{ validator: validateUserName, trigger: 'blur' }],
  passWord: [{ validator: validatePassWord, trigger: 'blur' }]
})

//提交
const submitForm = async (formEl) => {
  
  if (!formEl) return
  // console.log("formEl存在")
  await formEl.validate((valid) => {
    // console.log("进入验证程序")
    if (valid) {
      //表单内容校验成功，可以提交
      //  console.log("通过表单验证")
      if(fromType.value){
        //当前为注册页面
        userAuthentication(loginForm).then(({data})=>{
          if(data.code===10000){
            ElMessage.success('注册成功！')
          }
        })
      }else{
        //当前为登陆页面
        login(loginForm).then((data)=>{
          //  console.log(data)
          if(data.code===10000){
            
            //登陆成功后在本地保存token和用户信息
            localStorage.setItem('pz_token',data.data.token)
            localStorage.setItem('pz_userInfo',JSON.stringify(data.data.userInfo))
            //获取用户菜单权限
            menuPermissions().then((data)=>{
              store.commit('dynamicMenu',data.data)
              toRaw(routerList.value).forEach(element => {
                router.addRoute('main',element)
              });
              router.push('/')
            })
            // router.push('/')
          }
        })
      }
    } else {
      //校验失败
      console.log('error submit!')
    }
  })
}

//登录注册跳转链接切换
const handleChange=()=>{
  fromType.value=fromType.value?0:1
}

</script>

<style lang="less" scoped>
.el-link {
  margin-right: 8px;
}
:deep(.el-card__header) {
    padding: 0
  }
  .login-container {
    height: 100%;
    .card-header{
      background-color: #899fe1;
      img {
        width: 430px;
      }
    }
    .jump-link {
      text-align: right;
      margin-bottom: 10px;
    }
  }
</style>
